import MySQL
import Visualization
import Config as C


def resolve(dist_id):
    sql = 'SELECT * FROM `tpch_distribution` WHERE `id`=' + str(dist_id)
    dist = MySQL.query(sql)[0]
    for i in range(C.DEFAULT_DATA_START, C.DEFAULT_DATA_END + C.DEFAULT_DATA_DELTA - 1, C.DEFAULT_DATA_DELTA):
        data_table = dist['table'] + '_' + str(i) + 'w'
        column = dist['column']
        where_clause = dist['where_clause']
        if where_clause == 'null':
            where_clause = ''
        else:
            where_clause = ' WHERE ' + where_clause
        sql = 'SELECT VAR_POP({column}) AS variance FROM {data_table} {where_clause}'.format(column=column, data_table=data_table, where_clause=where_clause)
        variance = MySQL.query(sql)[0]['variance']
        MySQL.save('tpch_variance', {
            'variance': variance,
            'table': data_table,
            'column': column,
            'group': dist_id
        })


def draw(dist_id):
    sql = 'SELECT * FROM `tpch_variance` WHERE `group`=' + str(dist_id)
    variances = MySQL.query(sql)
    x = []
    y = []
    for row in variances:
        x.append(row['table'])
        y.append(row['variance'])
    maps = {'variance': {'x': x, 'y': y}}
    Visualization.draw(maps, chart_type='line')


if __name__ == '__main__':
    # resolve(4)
    draw(4)
